/*
 * Copyright 2011 Alex Paréj.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.mkdir.util;

import java.util.Random;

/**
 *
 * @author Alex Paréj
 */
public final class JelszoUtil {

    private final static String betuk = "abcdefghijklmnopqrstuvwxyz";
    private final static String szamok = "0123456789";

    private JelszoUtil() {
    }

    public static String jelszoGeneralasa(int kisbetu, int nagybetu, int szam, int hossz) {
        if (kisbetu < 0 || nagybetu < 0 || szam < 0 || hossz <= 0 || hossz < (kisbetu + nagybetu + szam)) {
            throw new IllegalArgumentException();
        }
        StringBuilder jelszo = new StringBuilder();
        Random rnd = new Random();
        //Kotelezo karakterek letrehozasa
        jelszo.append(getVeletlenKarakter(betuk, kisbetu));
        jelszo.append(getVeletlenKarakter(betuk, nagybetu).toUpperCase());
        jelszo.append(getVeletlenKarakter(szamok, szam));
        int maradek = hossz - kisbetu - nagybetu - szam;
        //Maradek hossz feltoltese
        for (int i = 0; i < maradek; i++) {
            switch (rnd.nextInt(3)) {
                case 0: {
                    jelszo.append(getVeletlenKarakter(betuk));
                    break;
                }
                case 1: {
                    jelszo.append(getVeletlenKarakter(betuk).toUpperCase());
                    break;
                }

                case 2: {
                    jelszo.append(getVeletlenKarakter(szamok));
                    break;
                }
            }
        }
        return StringUtil.osszekever(jelszo.toString());
    }

    private static String getVeletlenKarakter(String honnan, int hanyat) {
        if (StringUtil.isUres(honnan) || hanyat < 0) {
            throw new IllegalArgumentException();
        }
        Random rnd = new Random();
        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < hanyat; i++) {
            ret.append(honnan.charAt(rnd.nextInt(honnan.length())));
        }
        return ret.toString();
    }

    private static String getVeletlenKarakter(String honnan) {
        return getVeletlenKarakter(honnan, 1);
    }
}
